using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

//枚举控制敌人状态 站桩 巡逻 追击 死亡
public enum EnemyStates { GUARD, PATROL, CHASE, DEAD }
[RequireComponent(typeof(NavMeshAgent))]
public class EnemyController : MonoBehaviour
{
    public EnemyStates enemyStates;
    private NavMeshAgent agent;
    private Animator animator;

    [Header("基础设置")]
    public float sightRadius;//检测范围
    private GameObject attackObject;//攻击目标
    public bool isGuard;//是否是站桩敌人
    public float speed;//移动速度
    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
        speed = agent.speed;
    }

    private void Update()
    {
        SwitchStates();
    }

    //状态切换
    void SwitchStates()
    {
        if (FindPlayer())
        {
            enemyStates = EnemyStates.CHASE;
            Debug.Log("发现玩家");
            animator.SetBool("Chase", true);
            animator.SetBool("Follow", true);
            animator.SetBool("Walk", false);
        }
        else
        {
           
            animator.SetBool("Follow", false);
            animator.SetBool("Chase", false);
            if (isGuard)
            {
                enemyStates = EnemyStates.GUARD;
                animator.SetBool("Walk", false);
            }
            else
            {
                enemyStates = EnemyStates.PATROL;
                animator.SetBool("Walk", true);
            }

        }

        switch (enemyStates)
        {
            case EnemyStates.GUARD:
                break;
            case EnemyStates.PATROL:
                break;
            case EnemyStates.CHASE:
                //追击敌人
                agent.speed = speed;
                //设置该位置为导航目标点
                agent.SetDestination(attackObject.transform.position);
                //在攻击范围则攻击
                break;
            case EnemyStates.DEAD:
                break;
        }
    }

    //查找玩家
    bool FindPlayer()
    {
        //创建一个球形范围，获取范围内的全部碰撞体
        var collider = Physics.OverlapSphere(transform.position, sightRadius);
        foreach (var target in collider)
        {
            if (target.CompareTag("Player"))
            {
                //绑定攻击对象
                attackObject = target.gameObject;
                return true;
            }
        }
        attackObject = null;
        return false;
    }
}
